<?php

namespace WsdServer\Lib\Log;

class Log
{
    const INFO = 'info';

    const DEBUG = 'debug';

    private static $logger;

    protected $name;

    public function __construct($name)
    {
        $this->name = $name;
    }

    public static function getInstance($name = 'debug')
    {
        if (is_null(static::$logger)) {
            static::$logger = new self($name);
        }

        return static::$logger;
    }

    public static function setLogger($logger)
    {
        self::$logger = $logger;
    }

    public function debugLog($message, array $context = [], $name = 'FundsManager')
    {
        $this->setName($name);
        return config('funds_manager.DEBUG', false) && $this->addRecord($message, $context, self::DEBUG);
    }

    public function infoLog($message, array $context = [], $name = 'FundsManager')
    {
        $this->setName($name);
        return $this->addRecord($message, $context, self::INFO);
    }

    protected function addRecord($message, $context, $type)
    {
        $format = '[%s] [%s] %s '. PHP_EOL;
        if (!empty($context)) {
            $format .= '%s' . PHP_EOL;
        }
        $message = sprintf($format, date("H:i:s"), $type, $message, var_export($context, true));
        $filename = __APP_LOGS_PATH__ . '/' . $this->name . '.log.' . date('Ymd');
        return file_put_contents($filename, $message, FILE_APPEND);
    }

    public static function __callStatic($method, $args)
    {
        return call_user_func_array([self::getInstance(), $method.'Log'], $args);
    }

    protected function setName($name)
    {
        return $this->name = $name;
    }
}